<template>
  <div class="app-container">
    <el-form :inline="true" :model="listQuery" size="small" label-width="100px">
      <el-form-item label="输入搜索：">
        <el-input v-model="listQuery.orderSn" class="input-width" placeholder="订单编号"></el-input>
      </el-form-item>
      <el-form-item label="收货人：">
        <el-input v-model="listQuery.receiverKeyword" class="input-width" placeholder="收货人姓名/手机号码"></el-input>
      </el-form-item>
      <el-form-item label="提交时间：">
        <el-date-picker class="input-width" v-model="listQuery.createTime" value-format="YYYY-MM-DD" type="date" placeholder="请选择时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="订单状态：">
        <el-select v-model="listQuery.status" class="input-width" placeholder="全部" clearable>
          <el-option v-for="item in ORDER_STATUS_MAP" :key="item.value" :label="item.label" :value="item.value"> </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="订单分类：">
        <el-select v-model="listQuery.orderType" class="input-width" placeholder="全部" clearable>
          <el-option v-for="item in ORDER_TYPE_MAP" :key="item.value" :label="item.label" :value="item.value"> </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="订单来源：">
        <el-select v-model="listQuery.sourceType" class="input-width" placeholder="全部" clearable>
          <el-option v-for="item in ORDER_SOURCE_TYPE_MAP" :key="item.value" :label="item.label" :value="item.value"> </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearchList" size="small"> 搜索 </el-button>
        <el-button @click="handleResetSearch" size="small"> 重置 </el-button>
      </el-form-item>
    </el-form>
    <div class="table-container">
      <el-table
        ref="orderTable"
        :data="list"
        height="100%"
        style="width: 100%"
        v-loading="listLoading"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="60" align="center"></el-table-column>
        <el-table-column label="编号" width="80" align="center">
          <template #default="scope">{{ scope.row.id }}</template>
        </el-table-column>
        <el-table-column label="订单编号" width="180" align="center">
          <template #default="scope">{{ scope.row.orderSn }}</template>
        </el-table-column>
        <el-table-column label="提交时间" width="180" align="center">
          <template #default="scope">{{ formatDateTime(scope.row.createTime) }}</template>
        </el-table-column>
        <el-table-column label="用户账号" align="center">
          <template #default="scope">{{ scope.row.memberUsername }}</template>
        </el-table-column>
        <el-table-column label="订单金额" width="120" align="center">
          <template #default="scope">￥{{ scope.row.totalAmount }}</template>
        </el-table-column>
        <el-table-column label="支付方式" width="120" align="center">
          <template #default="scope">{{ PAY_TYPE_DICT[scope.row.payType] }}</template>
        </el-table-column>
        <el-table-column label="订单来源" width="120" align="center">
          <template #default="scope">{{ ORDER_SOURCE_TYPE_DICT[scope.row.sourceType] }}</template>
        </el-table-column>
        <el-table-column label="订单状态" width="120" align="center">
          <template #default="scope">{{ ORDER_STATUS_DICT[scope.row.status] }}</template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template #default="scope">
            <el-button size="small" link @click="handleViewOrder(scope.row)">详情</el-button>
            <el-button size="small" link @click="handleCloseOrder(scope.row)" v-show="scope.row.status === 0">关闭订单</el-button>
            <el-button size="small" link @click="handleDeliveryOrder(scope.row)" v-show="scope.row.status === 1">订单发货</el-button>
            <el-button size="small" link @click="handleViewLogistics" v-show="scope.row.status === 2 || scope.row.status === 3">
              订单跟踪
            </el-button>
            <el-button size="small" link type="danger" @click="handleDeleteOrder(scope.row)" v-show="scope.row.status === 4">
              删除订单
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="batch-operate-container">
      <el-select size="small" v-model="operateType" placeholder="批量操作">
        <el-option v-for="item in ORDER_OPERATE_STATUS_MAP" :key="item.value" :label="item.label" :value="item.value"> </el-option>
      </el-select>
      <el-button class="search-button" @click="handleBatchOperate()" type="primary" size="small"> 确定 </el-button>
    </div>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        v-model:current-page="listQuery.pageNum"
        :page-size="listQuery.pageSize"
        :page-sizes="[5, 10, 15]"
        :total="total"
      >
      </el-pagination>
    </div>
    <el-dialog title="关闭订单" v-model="closeOrder.dialogVisible" width="30%">
      <span style="vertical-align: top">操作备注：</span>
      <el-input style="width: 80%" type="textarea" :rows="5" placeholder="请输入内容" v-model="closeOrder.content"> </el-input>
      <template #footer>
        <el-button @click="closeOrder.dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleCloseOrderConfirm">确 定</el-button>
      </template>
    </el-dialog>
    <logistics-dialog v-model="logisticsDialogVisible"></logistics-dialog>
  </div>
</template>
<script setup lang="ts">
import { fetchList, closeOrder as closeOrderApi, deleteOrder as deleteOrderApi } from '@/api/order'
import LogisticsDialog from '@/views/oms/order/components/logisticsDialog.vue'
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import {
  ORDER_SOURCE_TYPE_MAP,
  ORDER_STATUS_MAP,
  ORDER_TYPE_MAP,
  ORDER_OPERATE_STATUS_MAP,
  ORDER_STATUS_DICT,
  ORDER_SOURCE_TYPE_DICT,
  PAY_TYPE_DICT,
} from '@/constant'
import type { Order } from '@/models/order'
import { formatDateTime } from '@/utils/format'

defineOptions({ name: 'OrderList' })

const router = useRouter()
const listQuery = ref<any>({})
const listLoading = ref(true)
const list = ref<Order[]>([])
const total = ref(0)
const operateType = ref<number>()
const multipleSelection = ref<Order[]>([])
const closeOrder = ref<any>({
  dialogVisible: false,
  content: null,
  orderIds: [],
})

const logisticsDialogVisible = ref(false)
getList()

function handleResetSearch() {
  listQuery.value = { pageNum: 1, pageSize: 10 }
}
function handleSearchList() {
  listQuery.value.pageNum = 1
  getList()
}
function handleSelectionChange(val: Order[]) {
  multipleSelection.value = val
}
function handleViewOrder(row: Order) {
  router.push({ path: '/oms/order/detail', query: { id: row.id } })
}
function handleCloseOrder(row: Order) {
  closeOrder.value.dialogVisible = true
  closeOrder.value.orderIds = [row.id]
}
function handleDeliveryOrder(row: Order) {
  let listItem = covertOrder(row)
  router.push({ path: '/oms/order/deliver', query: { list: JSON.stringify([listItem]) } })
}
function handleViewLogistics() {
  logisticsDialogVisible.value = true
}
function handleDeleteOrder(row: Order) {
  deleteOrder(row.id + '')
}
function handleBatchOperate() {
  if (multipleSelection.value == null || multipleSelection.value.length < 1) {
    ElMessage.success('请选择要操作的订单')
    return
  }
  if (operateType.value === 1) {
    //批量发货
    let list = multipleSelection.value.filter((item) => item.status === 1).map((item) => covertOrder(item))
    if (list.length === 0) {
      ElMessage.success('选中订单中没有可以发货的订单')
      return
    }
    router.push({ path: '/oms/order/deliver', query: { list: JSON.stringify(list) } })
  } else if (operateType.value === 2) {
    //关闭订单
    closeOrder.value.orderIds = multipleSelection.value.map((item) => item.id)
    closeOrder.value.dialogVisible = true
  } else if (operateType.value === 3) {
    deleteOrder(multipleSelection.value.map((item) => item.id).join(','))
  }
}
function handleSizeChange(val: number) {
  listQuery.value.pageNum = 1
  listQuery.value.pageSize = val
  getList()
}
function handleCurrentChange(val: number) {
  listQuery.value.pageNum = val
  getList()
}
async function handleCloseOrderConfirm() {
  if (closeOrder.value.content == null || closeOrder.value.content === '') {
    ElMessage.success('操作备注不能为空')
    return
  }
  let params = {
    ids: closeOrder.value.orderIds,
    note: closeOrder.value.content,
  }
  await closeOrderApi(params)
  closeOrder.value.orderIds = []
  closeOrder.value.dialogVisible = false
  getList()
  ElMessage.success('修改成功')
}
async function getList() {
  listLoading.value = true
  const response = await fetchList(listQuery.value)
  listLoading.value = false
  list.value = response.data.data.list
  total.value = response.data.data.total
}
async function deleteOrder(ids: string) {
  await ElMessageBox.confirm('是否要进行该删除操作?', '提示', { type: 'warning' })
  await deleteOrderApi({ ids })
  ElMessage.success('删除成功')
  getList()
}
function covertOrder(order: Order) {
  let address = '' + order.receiverProvince + order.receiverCity + order.receiverRegion + order.receiverDetailAddress
  let listItem = {
    orderId: order.id,
    orderSn: order.orderSn,
    receiverName: order.receiverName,
    receiverPhone: order.receiverPhone,
    receiverPostCode: order.receiverPostCode,
    address: address,
    deliveryCompany: null,
    deliverySn: null,
  }
  return listItem
}
</script>
<style scoped>
.input-width {
  width: 203px;
}
</style>
